﻿using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace IsoStorageManagerLib
{
    public static class IsoStorageEx
    {
        public static readonly JsonSerializer jsonSerializer 
            = new JsonSerializer { NullValueHandling = NullValueHandling.Ignore, MissingMemberHandling = MissingMemberHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore };

        // Sync T
        public static bool WriteJson<T>(this JsonTextWriter writer, T content)
        {
            writer.Formatting = Formatting.Indented;

            try { jsonSerializer.Serialize(writer, content); return true; }
            catch (Exception) { return false; }
        }

        public static T ReadJson<T>(this JsonTextReader reader)
        {
            return jsonSerializer.Deserialize<T>(reader);
        }

        // Async T
        public static async Task<bool> WriteJsonAsyncTask<T>(this JsonTextWriter writer, T content)
        {
            writer.Formatting = Formatting.Indented;
            return await TaskEx.Run(() =>
            {
                try { jsonSerializer.Serialize(writer, content); return true; }
                catch (Exception) { return false; }
            });
        }

        public static async Task<T> ReadJsonAsyncTask<T>(this JsonTextReader reader)
        {
            return await TaskEx.Run(() => jsonSerializer.Deserialize<T>(reader));
        }

        // Async strings
        public static async Task<bool> WriteAsyncThread(this StreamWriter writer, String content)
        {
            return await Task.Factory.StartNew(() =>
            {
                try { writer.Write(content); return true; }
                catch (Exception) { return false; }
            });
        }

        public static async Task<string> ReadAsyncThread(this StreamReader reader)
        {
            return await Task.Factory.StartNew<String>(reader.ReadToEnd);
        }


        // Misc stuff
        public static void CreateFolderIfNecessary(this IsolatedStorageFile isoFile, string fileName)
        {
            var directoryPath = Path.GetDirectoryName(fileName);
            if (!String.IsNullOrEmpty(directoryPath) && !isoFile.DirectoryExists(directoryPath))
                isoFile.CreateDirectory(directoryPath);
        }

    }
}
